﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ElectronStoreDAL;
using WebManagement;

namespace BackEnd
{
	public partial class Product : WebManagement.UserAuthentificatedPage
	{
		private ElectronStoreSource dataSource = new ElectronStoreSource();
		private ElectronStoreDAL.Product currentProduct = new ElectronStoreDAL.Product();
		private List<ElectronStoreDAL.Category> fullListCategories = new List<ElectronStoreDAL.Category>();
 
		private int currentIdCategory;
		private int currentIdProduct;
		private bool isNewProduct = true;

		public Product() : base(GeneralResource.urlLogin, GeneralResource.nameCookie) { }

		public List<ElectronStoreDAL.Category> ListCategory
		{
			get
			{
				if (dataSource != null)
					return dataSource.GetCategories();
				else
					return null;
			}
		}


		protected void Page_Load(object sender, EventArgs e)
		{
			int.TryParse(Request.Params["catId"], out currentIdCategory);
			if (int.TryParse(Request.Params["prodId"], out currentIdProduct))
			{
				if (currentIdProduct > 0)
				{
					currentProduct = dataSource.GetProductById(currentIdProduct);
					isNewProduct = false;
				}
			}

			if (!IsPostBack)
			{
				fullListCategories.AddRange(currentProduct.Categories);
				Session[GeneralResource.newCategories] = fullListCategories;
			}
			else
			{
				fullListCategories = Session[GeneralResource.newCategories] as List<ElectronStoreDAL.Category>;
			}
		}


		protected void Page_PreRender(object sender, EventArgs e)
		{
			if (!IsPostBack)
			{
				//initialize the controls of the current product
				if (!isNewProduct)
				{
					tbxName.Text = currentProduct.Name;
					tbxPrice.Text = string.Format("{0:F2}", currentProduct.CurrentPrice);
					if (!string.IsNullOrEmpty(currentProduct.Info))
						tbxInfo.Text = currentProduct.Info;
					string path = PathManager.UrlSmallImage(GeneralResource.urlSmallImages, currentProduct.ProductID);
					if (System.IO.File.Exists(Server.MapPath(path)))
						imgProduct.ImageUrl = path + "?t=" + DateTime.Now.ToString();
				}

				if (ListCategory != null)
					ddlCategory.DataSource = ListCategory;
				ddlCategory.DataBind();

				if (ddlCategory.Items != null)
				{
					ListItem item = ddlCategory.Items.FindByValue(currentIdCategory.ToString());
					if (item != null)
						item.Selected = true;
				}
			}

			rpCategory.DataSource = fullListCategories;
			rpCategory.DataBind();

		}	//protected void Page_PreRender


		protected void rpCategory_ItemDataBound(object sender, RepeaterItemEventArgs e)
		{
			if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
			{
				ElectronStoreDAL.Category category = e.Item.DataItem as ElectronStoreDAL.Category;

				if (category != null)
				{
						Label lblCat = e.Item.FindControl("lblCatName") as Label;
						if (lblCat != null)
							lblCat.Text = category.Name;

					ImageButton btnDel = e.Item.FindControl("btnDelCategory") as ImageButton;
					if (btnDel != null)
						btnDel.CommandArgument = category.CategoryID.ToString();
				}
			}

		}	//protected void rpCategory_ItemDataBound


		protected void btnAddCategory_Click(object sender, EventArgs e)
		{
			ElectronStoreDAL.Category changeCategory = null;
			int idCat;
			if (int.TryParse(ddlCategory.SelectedValue, out idCat))
				changeCategory = dataSource.GetCategoryById(idCat);

			if (changeCategory != null && !fullListCategories.Contains(changeCategory))
			{
				fullListCategories.Add(changeCategory);
				Session[GeneralResource.newCategories] = fullListCategories;
			}
		}


		protected void btnDelCategory_Click(object sender, EventArgs e)
		{
			ImageButton btn = sender as ImageButton;
			if (btn == null)
				return;

			int idCat;
			if (int.TryParse(btn.CommandArgument, out idCat))
			{
				ElectronStoreDAL.Category changeCategory = dataSource.GetCategoryById(idCat);
				if (changeCategory != null)
				{
					fullListCategories.Remove(changeCategory);
					Session[GeneralResource.newCategories] = fullListCategories;
				}
			}
		}


		protected void btnPrviewImage_Click(object sender, EventArgs e)
		{
			byte[] buffer;
			if (fuploadImg.HasFile)
			{
				buffer = new byte[fuploadImg.PostedFile.ContentLength];
				fuploadImg.PostedFile.InputStream.Read(buffer, 0, buffer.Length);
				Session[GeneralResource.keyBufferImg] = buffer;
				imgPreview.ImageUrl = GeneralResource.urlImageHandler;
			}
		}


		protected void btnSave_Click(object sender, EventArgs e)
		{
			byte[] buffer = null;
			if (Session[GeneralResource.keyBufferImg] != null)
				buffer = Session[GeneralResource.keyBufferImg] as byte[];

			//fill the field the current product
			currentProduct.Name = tbxName.Text;
			currentProduct.CurrentPrice = Convert.ToDecimal(tbxPrice.Text);
			currentProduct.Info = tbxInfo.Text;

			//clear and fill list categories of the current product
			currentProduct.Categories.Clear();
			foreach (ElectronStoreDAL.Category cat in fullListCategories)
			{
				currentProduct.Categories.Add(cat);
				cat.Products.Add(currentProduct);
			}

			//update or add current product to database
			if (isNewProduct)
				dataSource.AddProduct(currentProduct);
			else
				dataSource.UpdateProduct(currentProduct);

			//save product image
			if (currentProduct.ProductID > 0)
			{
				if (fuploadImg.HasFile)
					fuploadImg.SaveAs(Server.MapPath(PathManager.UrlSmallImage(GeneralResource.urlSmallImages, currentProduct.ProductID)));
				else if (buffer != null)
				{
					System.IO.FileStream fstream = null;
					try
					{
						fstream = new FileStream(Server.MapPath(PathManager.UrlSmallImage(GeneralResource.urlSmallImages, currentProduct.ProductID)), FileMode.Create);
						fstream.Write(buffer, 0, buffer.Length);
					}
					catch (IOException ex)
					{
						WebManagement.ErrorLogger.LogError(ex);
					}
					finally
					{
						if (fstream != null)
							fstream.Close();
					}
				}
			}

			Response.Redirect(string.Format(GeneralResource.urlCatalog, currentIdCategory));

		}	//protected void btnSave_Click


		protected void btnCancel_Click(object sender, EventArgs e)
		{
			Response.Redirect(string.Format(GeneralResource.urlCatalog, currentIdCategory), true);
		}

	}	//public partial class Product

}	//namespace BackEnd